﻿using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using NHibernate.Criterion;
using Rodunu.Movies.Contracts;
using Rodunu.Movies.Data;
using Rodunu.Movies.Interfaces.Security;
using Rodunu.Movies.Interfaces.User;
using Rodunu.Movies.Logic.User;

namespace Rodunu.Movies.Logic.Validation
{
    public class ValidationLogic : Repository<UserVerification>, IUserValidation
    {
        private const int SALTSIZE = 5;

        public UserValidation Validate(string hash)
        {
            ISessionFactory sessionFactory = DBHelper.BuildConfiguration().Configure().BuildSessionFactory();
            ISession session = sessionFactory.OpenSession();
            UserVerification uv = null;
            UserValidation userValidation = null;
            UserInfo user = null;

            try
            {
                uv = session.CreateCriteria(typeof (UserVerification))
                    .Add(Restrictions.Eq("VerificationToken", System.Web.HttpUtility.UrlEncode(hash)))
                    .UniqueResult<UserVerification>();
                
                user = uv.UserInfo;
                userValidation = new UserValidation {UserId = user.Id};

                if (CheckStaleToken(uv))
                {
                    userValidation.Validity = UserValidation.TokenValidity.Valid;
                    session.Close();
                    return userValidation;
                }

                userValidation.Validity = UserValidation.TokenValidity.Stale;
                session.Close();
                return userValidation;
            }
            catch (Exception)
            {
                session.Close();
                userValidation = new UserValidation {UserId = 0, Validity = UserValidation.TokenValidity.Invalid};
                return userValidation;
            }
        }

        private bool CheckStaleToken(UserVerification userVerification)
        {
            TimeSpan ts = DateTime.Now - userVerification.DateEntered;
            return ts.Days <= 15;
        }

        public string CreateValidationHash(UserInfo identifiable)
        {
            string salt = UserHelper.CreateSalt(SALTSIZE);
            string hash = System.Web.HttpUtility.UrlEncode(UserHelper.CreatePasswordHash(identifiable.UserName, salt));
            Create(new UserVerification {UserInfo = identifiable, VerificationToken = hash, DateEntered = DateTime.Now});
            return hash;
        }
    }
}
